package com.enjoyor.soa.traffic.frame.security.fifter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.PathMatcher;

import com.enjoyor.filter.SSOClientfilter;
import com.enjoyor.soa.traffic.frame.constant.AuthConstant;
import com.enjoyor.soa.traffic.frame.security.bean.result.AuthorizeResult;
import com.enjoyor.soa.traffic.frame.support.util.HttpClientUtil;
import com.enjoyor.soa.traffic.util.base.JSONUtil;
import com.enjoyor.soa.traffic.util.helper.JsonHelper;

public class SSOFilter implements Filter {

    private static String startUp = null;
    // http://192.168.91.152:8081/uums-server/token/check
    private static String checkUrl = null;
    // a7e8ff20-678a-40bd-986b-9f0ee7fec307
    private static String systemKey = null;
    // private static String service = "http://localhost:10400/web/index.html";
    // http://192.168.91.152:8081/uums-server
    private static String server = null;
    private static String excludePaths = null;

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (!startUp.equals("1")) {
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getServletPath().indexOf("swagger-ui.html") != -1) {
            filterChain.doFilter(request, response);
            return;
        }

        if ((excludePaths != null) && (!"".equals(excludePaths))) {
            String requestPath = request.getRequestURI();
            PathMatcher matcher = new AntPathMatcher();
            for (String excludePath : excludePaths.split(",")) {
                if (matcher.match(excludePath, requestPath)) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
        }

        String token = request.getParameter("token");

        if (!StringUtils.isBlank(token)) {
            MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
            params.add("token", token);
            params.add("systemKey", systemKey);
            String result = HttpClientUtil.client(checkUrl, HttpMethod.POST, params);
            AuthorizeResult authorizeResult = JSONUtil.toBean(result, AuthorizeResult.class);
            if (authorizeResult.getAppCode().equals("0")) {
                request.setAttribute(AuthConstant.CONST_TOKEN, token);
                request.setAttribute(AuthConstant.CONST_USER,
                        JsonHelper.beanToJsonStr(authorizeResult.getResultList()));
                request.setAttribute("systemKey", systemKey);
                setCookie("token", token, response);
                filterChain.doFilter(request, response);
                return;
            } else {
                response.sendRedirect(
                        server + "?service=" + request.getRequestURL().toString() + "&systemKey=" + systemKey);
            }
        } else
            response.sendRedirect(
                    server + "?service=" + request.getRequestURL().toString() + "&systemKey=" + systemKey);
        return;
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        if (filterConfig.getInitParameter("startUp") != null)
            startUp = filterConfig.getInitParameter("startUp");
        if (filterConfig.getInitParameter("server") != null)
            server = filterConfig.getInitParameter("server");
        if (filterConfig.getInitParameter("checkUrl") != null)
            checkUrl = filterConfig.getInitParameter("checkUrl");
        if (filterConfig.getInitParameter("systemKey") != null)
            systemKey = filterConfig.getInitParameter("systemKey");
        if (filterConfig.getInitParameter("excludePaths") != null)
            excludePaths = filterConfig.getInitParameter("excludePaths");
        

        //clientfilter配置
        Map<String, String> map = new HashMap<String, String>();
		map.put("SSOService", server);
		map.put("validationUrl", checkUrl);
		map.put("excludePaths", excludePaths);
		map.put("systemKey", systemKey);
		map.put("startUp", startUp);
        SSOClientfilter.setConfig(map);
    }

    private void setCookie(String name, String token, HttpServletResponse response) {
        Cookie cookie = new Cookie(name, token);
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

}
